<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ include file="/WEB-INF/views/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link href="${cs}/js/easyui/themes/default/easyui.css" rel="stylesheet" type="text/css" />
	<title>Insert title here</title>
	<style type="text/css">
	</style>
  <script type="text/javascript">
	var datagrid;
	var rowEditor=undefined;
	var buttonFlag = null;
	$(function(){
		datagrid=$("#dg").datagrid({
			url:"${cs}/cs/user/role/list",//加载的URL
		    isField:"id",
			pagination:true,//显示分页
			pageSize:10,//分页大小
			pageList:[10,15,20],//每页的个数
			fit:true,//自动补全
			fitColumns:true,
			iconCls:"icon-save",//图标
			columns:[[      //每个列具体内容
		              {field:'id', hidden:true },   
		              {field:'name', title:'角色名',width:"20%",align:'center' },
		              {field:'desc', title:'简介',width:"40%",align:'center' },
		              {field:'state', title:'状态',  width:"30%", align:'center',
			            	formatter: function(val,row, index) {
			            		if (val == 1){
			            			return '<span style="color:#2575ed;">正常('+val+')</span>';
			        			} else if (val == 0) {
			        				return '<span style="color:red;">停用('+val+')</span>';;
			        			}
			            	}  
			              },
		              {field:'function', title:'操作',  width:"11%", align:'center',
			            	formatter: function(val,row, index) {
			            		if (row.state == 1){
			            			return '<span class="function" onclick="selectfunction('+row.id+')">权限维护</span>';
			        			} 
			            	}  
			              }
		          ]],
			toolbar:[              //工具条
			        {text:"增加",iconCls:"icon-add",handler:function(){//回调函数
			        	 buttonFlag="add";
			        	 $('#dd').dialog('open');
			        }},
			        {text:"修改",iconCls:"icon-edit",handler:function(){
			        	buttonFlag="edit";
			        	var rows=datagrid.datagrid('getSelections');
			        	if(rows.length==1)
			        	{
			        		$.ajax({
	        					url : '${cs}/cs/user/role/edit'+rows[0].id,
	        					dataType : 'json',
	        					success : function(r) {
	        						if (r.id) {
	        							 $('#dd').dialog('open');
	        							 $("#id").val(r.id);
	        							 $("#name").textbox("setValue",r.name);
	        							 $("#desc").textbox("setValue",r.desc);
	        						} else {
	        							$.messager.alert('错误',"页面初始化失败！", 'error');
	        						}
	        					}
	        				});
			        	} else {
			        		$.messager.alert('错误', "只能选择一个数据进行修改", 'error');
			        	}
			        }},
			        {text:"启用",iconCls:"icon-remove",handler:function(){
			        	var rows=datagrid.datagrid('getSelections');
			        	if(rows.length<=0){
			        		$.messager.alert('警告','您没有选择','error');
			        	}else{
			        		var rows = datagrid.datagrid('getSelections');
			        		for(var i=0; i<rows.length; i++){
	        					if(rows[i].state == 1){
	        						$.messager.alert('错误', "请勿重复启用已开启的角色！", 'error');
				        			return;
	        					}
	        				}
			        		$.messager.confirm('确定','您确定要启用吗',function(t){
			        			if(t){
			        				var ids = [];
			        				var rows = datagrid.datagrid('getSelections');
			        				for(var i=0; i<rows.length; i++){
			        					ids.push(rows[i].id);
			        				}
			        				$.ajax({
			        					url : '${cs}/cs/user/role/updateStatus',
			        					data : 'status=1&ids='+ids.join(','),
			        					method: 'POST',
			        					type:'json',
			        					dataType : 'json',
			        					success : function(r) {
			        						if (r>0) {
			        							$.messager.show({
			        								msg : "操作成功",
			        								title : '成功'
			        							});
			        							datagrid.datagrid('reload');
			        						} else {
			        							$.messager.alert('错误',"操作失败", 'error');
			        						}
			        						datagrid.datagrid('unselectAll');
			        					}
			        				});
			        			
			        			}
			        		})
			        	}
			        }},
			        {text:"停用",iconCls:"icon-remove",handler:function(){
			        	var rows=datagrid.datagrid('getSelections');
			        	if(rows.length<=0){
			        		$.messager.alert('警告','您没有选择','error');
			        	}else{
			        		var rows = datagrid.datagrid('getSelections');
			        		for(var i=0; i<rows.length; i++){
	        					if(rows[i].state == 0){
	        						$.messager.alert('错误', "请勿重复停用已停用状态的用户！", 'error');
				        			return;
	        					}
	        				}
			        		$.messager.confirm('确定','您确定要停用吗',function(t){
			        			if(t){
			        				var ids = [];
			        				var rows = datagrid.datagrid('getSelections');
			        				for(var i=0; i<rows.length; i++){
			        					ids.push(rows[i].id);
			        				}
			        				$.ajax({
			        					url : '${cs}/cs/user/role/updateStatus',
			        					data : 'status=0&ids='+ids.join(','),
			        					method: 'POST',
			        					type:'json',
			        					dataType : 'json',
			        					success : function(r) {
			        						if (r>0) {
			        							$.messager.show({
			        								msg : "操作成功",
			        								title : '成功'
			        							});
			        							datagrid.datagrid('reload');
			        						} else {
			        							$.messager.alert('错误',"操作失败", 'error');
			        						}
			        						datagrid.datagrid('unselectAll');
			        					}
			        				});
			        			
			        			}
			        		})
			        	}
			        }}
			  ],
				onLoadSuccess:function(data){
				   	  $('.function').linkbutton({
				   	      iconCls: 'icon-edit'
				   	  });
			   	  }
		});
		 $('#dd').dialog({
             title: buttonFlag=="add"?"增加角色":"角色维护",
             closed:true,
             modal: true, //dialog继承自window，而window里面有modal属性，所以dialog也可以使用
             toolbar: [{
					text:'Ok',
				iconCls:'icon-ok',
				handler:function(){
					var pnodes= GetNode('fnode'), cnodes=GetNode('child');
					$('#ff').form('submit',{
						onSubmit:function(){
							var isValid = $(this).form('validate');
							if(isValid) {
								if(!!pnodes && !!cnodes){
									$("#functions").val(pnodes+","+cnodes);
								}
							}
							return isValid;
						},
						success: function(r){
							if (r>0) {
    							$.messager.show({
    								msg : '操作成功',
    								title : 'Success!'
    							});
    							$('#ff').form('clear');
    							$('#dd').dialog('close');
    							datagrid.datagrid('reload');
    						} else {
    							$.messager.alert('错误', '操作失败', 'error');
    						}
						}
					});
				
				}
			},{
				text:'Cancel',
				handler:function(){
					$('#dd').dialog('close');
					$('#ff').form('clear');
				}
			}],
			onClose: function() {
				$('#ff').form('clear');
				datagrid.datagrid('unselectAll');
				datagrid.datagrid('reload');
			}
         });
		 $('#function').dialog({
             title: "权限维护",
             closed:true,
             modal: true, //dialog继承自window，而window里面有modal属性，所以dialog也可以使用
             toolbar: [{
					text:'Ok',
				iconCls:'icon-ok',
				handler:function(){
					var pnodes= GetNode('fnode'), cnodes=GetNode('child');
					$('#menu').form('submit',{
						onSubmit:function(){
							var isValid = $(this).form('validate');
							if(isValid) {
								if(!!pnodes && !!cnodes){
									$("#functions").val(pnodes+","+cnodes);
								}
							}
							return isValid;
						},
						success: function(r){
							if (r>0) {
    							$.messager.show({
    								msg : '操作成功',
    								title : 'Success!'
    							});
    							$('#menu').form('clear');
    							$('#function').dialog('close');
    							datagrid.datagrid('reload');
    						} else {
    							$.messager.alert('错误', '操作失败', 'error');
    						}
						}
					});
				
				}
			},{
				text:'Cancel',
				handler:function(){
					$('#function').dialog('close');
				}
			}],
			onClose: function() {
				var nodes = $('#privilege-tree').tree('getChecked');
		    	for(var i=0;i<nodes.length;i++){
		    		 $('#privilege-tree').tree('uncheck',nodes[i].target);  
		    	}
				datagrid.datagrid('unselectAll');
				datagrid.datagrid('reload');
			}
         });
		$("#btn_search").click(function(){
			var param = $("#searchForm").serializeJson();
			datagrid.datagrid('load', param);
		});
		$('#state').combobox({
			 data: [{"name": '全部', "id": '-1'},{"name": '未启用', "id": '0'},{"name": '已启用', "id": '1'}],
			 valueField:'id',
			 textField:'name',
			 value:'-1'
		 });
	});
	
	function initTree(privileges) {
		 $('#privilege-tree').tree({
			    checkbox: true,
			    url:'${cs}/cs/user/Menu/tree',
			    onLoadSuccess: function(node1, data) {
			    	if(privileges!=null){
				    	var array = privileges.split(',');
	                    for(var i=0;i<array.length;i++){
	                 	   if(array[i] != "") {
	                      	  var node = $('#privilege-tree').tree('find',array[i]); 
	                      	  if(node) $('#privilege-tree').tree('check',node.target);  
	                 	   }
	                    }  
			    	}
			    }
		   });
	}
	
	function GetNode(type){
        var node = $('#privilege-tree').tree('getChecked');
        var cnodes='';
        var pnodes='';
         var prevNode=''; //保存上一步所选父节点
        for(var i=0;i<node.length;i++){
            if($('#privilege-tree').tree('isLeaf',node[i].target)){
                cnodes+=node[i].id+',';  
                var pnode = $('#privilege-tree').tree('getParent',node[i].target); //获取当前节点的父节点
               if(prevNode!=pnode.id) //保证当前父节点与上一次父节点不同
               {
                    pnodes+=pnode.id+',';
                    prevNode = pnode.id; //保存当前节点
               }
            }
        }
        cnodes = cnodes.substring(0,cnodes.length-1);
        pnodes = pnodes.substring(0,pnodes.length-1);
        if(type=='child'){return cnodes;}
        else{return pnodes;};
    };	
    function selectfunction(id){
    	$.ajax({
			url : '${cs}/cs/user/role/edit'+id,
			dataType : 'json',
			success : function(r) {
				if (r.id) {
					 $('#function').dialog('open');
					 $("#roleid").val(r.id);
					 $("#roleName").textbox("setValue",r.name);
					 initTree(r.menuIds);
				} else {
					$.messager.alert('错误',"页面初始化失败！", 'error');
				}
			}
		});
    }
    </script>
</head>
<body style="padding:0 4px; margin:0;  overflow: hidden; ">
<div class="easyui-layout" style="width:100%;height:100%;" data-options="fit:true">
		<div title="角色管理" data-options="region:'north'" style="height:70px">
		 <form id="searchForm" >
			<table cellpadding="5">
				    		<tr>
				    			<td>角色名:</td>
				    			<td><input class="easyui-textbox" type="text" id="qRoleName"  name="name" ></input></td>
				    			<td>角色名:</td>
				    			<td><input class="easyui-combobox" type="text" data-options="panelHeight:'auto'" id="state"  name="state" ></input></td>
				    			<td ><a href="#" id="btn_search" class="easyui-linkbutton" data-options="iconCls:'icon-search'" style="width:80px">Search</a></td>
				    		</tr>
				    	</table>
				  </form>
		</div>
		<div data-options="region:'center'" >
			<table id="dg" >
			</table>
		</div>
		<div id="dd" title="My Dialog"  style="width:300px;height:380px; text-align: center; " data-options="closed:true"> 
				    <form id="ff" method="post" action="${cs}/cs/user/role/saveRole" >
				    		<input type="hidden" id="id" name="id">
				    		<div style="margin:10px 0">
								角色名:<input class="easyui-textbox" type="text" id="name"  name="name" data-options="required:true"></input>
							</div>
							<div style="margin:10px 0">
								简&nbsp;&nbsp;介:<input class="easyui-textbox" id="desc" name="desc" data-options="multiline:true,required:true"  style="width:171px;height:60px;">
							</div>
				    </form>
			</div>
			<div id="function" title="My Dialog"  style="width:300px;height:400px; text-align: center; " data-options="closed:true"> 
				    <form id="menu" method="post" action="${cs}/cs/user/role/saveRole" >
				    		<input type="hidden" id="roleid" name="id">
				    		<input type="hidden" id="functions" name="MenuIds">
				    		<div style="margin:10px 0">
								角色名:<input class="easyui-textbox" disabled="disabled" type="text" id="roleName"  name="name" data-options="required:true"></input>
							</div>
							<div style="margin:10px 0">
								<label class="selectTitle">请选择对应权限：</label>
								<div class="easyui-panel" style="padding:5px;">
									<ul id="privilege-tree" class="easyui-tree" data-options=""></ul>
								</div>
							</div>
				    </form>
			</div>
		</div>
</body>
</html>